import { isRef, onBeforeUnmount, onMounted, unref, watch, type Ref } from 'vue'

export default function useEventListener(
  target: Ref<EventTarget | null> | EventTarget,
  event: string,
  handler: (e: Event) => any
) {
  // isRef 判断一个对象是不是响应式对象
  if (isRef(target)) {
    watch(target, (newValue, oldValue) => {
      oldValue?.removeEventListener(event, handler)
      newValue?.addEventListener(event, handler)
    })
  } else {
    onMounted(() => {
      target.addEventListener(event, handler)
    })
  }
  // unref() 获取响应式对象的值，如果不是响应式对象返回值本身
  onBeforeUnmount(() => {
    unref(target)?.removeEventListener(event, handler)
  })
}
